package com.boss.thirteen.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.entity.MakeSalaryData;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.entity.SalaryPaymentRequisitionBack;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.salary.service.IRedisService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import com.boss.thirteen.service.IThirteenGenerateSalaryDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/thirteenSalaryGeneratePayment")
public class ThirteenSalaryGeneratePaymentController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(ThirteenSalaryGeneratePaymentController.class);

    @Autowired
    private IThirteenGenerateSalaryDataService iGenerateSalaryDataService;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;
    @Autowired
    private IRedisService redisService;


    /**
     * 生成工资数据
     * @param tokenid
     * @param makeSalaryData 要生成工资数据的单位
     * @return
     */
    @PostMapping("/makeSalaryDataAsync")
    public ApiResultDTO makeSalaryDataAsync(@RequestHeader("X-Token") String tokenid,
                                       @RequestBody MakeSalaryData makeSalaryData){
        try {
            UserDTO userDto = getUser(tokenid);
            Object re=redisService.get(userDto.getProvince()+"thirteenGenerateSalary");
            //查询缓存中该区划是否有在执行的生成操作
            if(!SysUtils.isNullOrEmpty(re)){
                return ApiResultDTO.error(ERROR_RSCODE, "已执行生成支付操作，请等待");
            }
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("生成工资数据--生成支付数据--生成");
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            Map<String,String> map =iGenerateSalaryDataService.makeSalaryDataAsyncRedis(tokenid, makeSalaryData,userDto);
            return ApiResultDTO.success(map);

        } catch (AppRuntimeException e) {
            e.printStackTrace();
            logger.error("生成工资数据失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成工资数据失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }


    /**
     * 检测生成工资的数据
     * @param tokenid
     * @param makeSalaryData 要生成工资数据的单位
     * @return
     */
    @PostMapping("/checkSalaryData")
    public ApiResultDTO checkSalaryData(@RequestHeader("X-Token") String tokenid,
                                            @RequestBody MakeSalaryData makeSalaryData){
        try {
            UserDTO userDto = getUser(tokenid);
            Map<String,Object> map =iGenerateSalaryDataService.checkSalaryData(tokenid, makeSalaryData,userDto);
            return ApiResultDTO.success(map);

        } catch (AppRuntimeException e) {
            e.printStackTrace();
            logger.error("检测生成工资数据失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("检测生成工资数据失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 查看支付生成进度
     * @param uuid
     * @return
     */
    @GetMapping("/getPaymentPercent")
    public ApiResultDTO  getPaymentPercent(@RequestParam(value = "uuid") String uuid,@RequestHeader("X-Token") String tokenid){
        try {
            UserDTO userDto = getUser(tokenid);
            Object re = redisService.get(uuid);

            if ("S".equals(re) || (re != null && re.toString().startsWith("F"))) {
                redisService.del(uuid);
                Object generateSalaryState = redisService.get(userDto.getProvince() + "thirteenGenerateSalary");
                if(generateSalaryState!=null) {
                    redisService.del(userDto.getProvince() + "thirteenGenerateSalary");
                }
            }
            return ApiResultDTO.success(re);
        }catch (Exception e) {
                e.printStackTrace();
                logger.error("检测生成工资数据失败", e.getMessage());
                return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 获取单位银行上传状态
     * @return
     */
    @GetMapping("/getBankDataStatus")
        public ApiResultDTO getBankDataStatus(@RequestParam("agencyIds") List<String> agencyIds) {
        try {
            boolean status = iGenerateSalaryDataService.getBankDataStatus(agencyIds);
            return ApiResultDTO.success(status);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("撤销支付失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, "获取银行上传状态失败");
        }
    }

    /**
     * 撤销支付
     * @param tokenid
     * @return
     */
    @PostMapping("/revokeSalaryData")
    public ApiResultDTO revokeSalaryData(@RequestHeader("X-Token") String tokenid,
                                         @RequestBody MakeSalaryData makeSalaryData) {
        try {
            UserDTO userDto = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDto.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDto.getAgency());
            operrateLogs.setUeserName(userDto.getName());
            operrateLogs.setOperateName("生成工资数据--生成支付数据--撤销生成");
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            iGenerateSalaryDataService.revokeSalaryData(tokenid, makeSalaryData,userDto);
            return ApiResultDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("已进入支付流程，无法撤销！", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 获取支付回单数据
     * @param agencyId
     * @param salaryMonth
     * @return
     */
    @GetMapping("/getPayBackData")
    public ApiResultDTO getPayBackData(@RequestHeader("X-Token") String tokenid,
                                       @RequestParam("agencyId") String agencyId,
                                       @RequestParam("salaryMonth") String salaryMonth) {
        try {
            UserDTO userDto = getUser(tokenid);
            Map<String, Object> queryParam = new HashMap<>(2);
            queryParam.put("agencyId", agencyId);
            queryParam.put("salaryMonth", salaryMonth);
            List<SalaryPaymentRequisitionBack> result = iGenerateSalaryDataService.getPayBackData(queryParam,tokenid,userDto);
            return ApiResultDTO.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取支付回单数据失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, "获取支付回单数据失败");
        }
    }

}
